#include <stdio.h>
#include <unistd.h>
#include "dlm_api.h"


int pipe_desc[2];

void DLM_init(int pipes[2]) {
	pipe_desc[0] = pipes[0];
	pipe_desc[1] = pipes[1];
}

int send_message(int request, int resource_id, int lock_type, long timeout) {
	struct message requestMessage;
	requestMessage.requestType = request;
	requestMessage.senderPid = getpid();
	requestMessage.resource_id = resource_id;
	requestMessage.lock_type = lock_type;
	requestMessage.timeout = timeout;
	requestMessage.returnValue = 0; //nieużywane przy żądaniu
	
	if (write(pipe_desc[PIPE_SEND],
	          &requestMessage,
	          sizeof(requestMessage)) != sizeof(requestMessage)) {
				  printf("[E]Client: Nie udalo sie zapisac do potoku");
				  return DLM_ERR_UKNOWN;
			  }
	return 0;
}

int read_reply() {
	struct message reply;
	read(pipe_desc[PIPE_RECV], &reply, sizeof(reply));
	
	return reply.returnValue;
}

int DLM_lock(int resource_id, int lock_type, long timeout) {
	if (send_message(DLM_REQ_LOCK, resource_id, lock_type, timeout)
			== DLM_ERR_UKNOWN) {
				printf("[E]Client: Nie udalo sie wyslac zadania blokady\n");
				return DLM_ERR_UKNOWN;
	}
	int retVal = read_reply();
	return retVal;
}

int DLM_trylock(int resource_id, int lock_type) {
	if (send_message(DLM_REQ_TRYLOCK, resource_id, lock_type, 0)
			== DLM_ERR_UKNOWN) {
				printf("[E]Client: Nie udalo sie wyslac sprawdzenia blokady\n");
				return DLM_ERR_UKNOWN;
	}
	return read_reply();
}

int DLM_unlock(int resource_id) {
	if (send_message(DLM_REQ_UNLOCK, resource_id, 0, 0)
			== DLM_ERR_UKNOWN) {
				printf("[E]Client: Nie udalo sie wyslac usunicia blokady\n");
				return DLM_ERR_UKNOWN;
	}
	int retVal = read_reply();
	return retVal;
}

int DLM_terminate_process() {
	if (send_message(DLM_TERMINATE_PROCESS, 0, 0, 0)
			== DLM_ERR_UKNOWN) {
				printf("[E]Client: Nie udalo sie wyslac zakonczenia procesu\n");
				return DLM_ERR_UKNOWN;
	}
	return read_reply();
}
